import cron from 'node-cron'

// 任务状态管理
class TaskManager {
  private tasks: Map<string, any> = new Map<string, any>()
  private isInitialized = false

  // 添加任务
  addTask(name: string, schedule: string, handler: () => Promise<void> | void, options: any = {}) {
    if (this.tasks.has(name)) {
      console.log(`⚠️  任务 ${name} 已存在，跳过添加`)
      return
    }

    const task = cron.schedule(schedule, async () => {
      const startTime = Date.now()
      try {
        console.log(`�� [${name}] 开始执行 - ${new Date().toLocaleString()}`)
        await handler()
        console.log(`✅ [${name}] 执行完成 - 耗时: ${Date.now() - startTime}ms`)
      } catch (error) {
        console.error(`❌ [${name}] 执行失败:`, error)
      }
    }, {
      scheduled: false, // 先不启动
      timezone: 'Asia/Shanghai',
      ...options
    })

    this.tasks.set(name, task)
    console.log(`�� 注册任务: ${name} (${schedule})`)
  }

  // 启动所有任务
  startAll() {
    if (this.isInitialized) {
      console.log('⚠️  任务已启动，跳过重复初始化')
      return
    }

    console.log('�� 启动所有定时任务...')
    let startedCount = 0

    this.tasks.forEach((task, name) => {
      try {
        task.start()
        startedCount++
        console.log(`▶️  [${name}] 已启动`)
      } catch (error) {
        console.error(`❌ [${name}] 启动失败:`, error)
      }
    })

    this.isInitialized = true
    console.log(`✅ 定时任务启动完成，共 ${startedCount} 个任务`)
  }

  // 停止所有任务
  stopAll() {
    console.log('�� 停止所有定时任务...')
    this.tasks.forEach((task, name) => {
      task.stop()
      console.log(`⏹️  [${name}] 已停止`)
    })
    this.isInitialized = false
  }

  // 获取任务状态
  getStatus() {
    const status: Record<string, boolean> = {}
    this.tasks.forEach((task, name) => {
      status[name] = task.running
    })
    return {
      initialized: this.isInitialized,
      taskCount: this.tasks.size,
      tasks: status
    }
  }
}

// 单例模式
export const taskManager = new TaskManager()